package com.lucky.carcodepro.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * JacksonConfig
 * <p>
 * 描述：时间统一格式化
 *
 * @author Annie
 * @version 2024/10/2 19:51
 */
@Configuration
public class JacksonConfig
{
    // 统一的时间格式
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Bean
    public ObjectMapper objectMapper()
    {
        ObjectMapper objectMapper = new ObjectMapper();

        // 注册模块以支持 Java 8 日期和时间 API
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));

        // 注册 JavaTimeModule 到 ObjectMapper
        objectMapper.registerModule(javaTimeModule);

        // 设置序列化日期格式（用于非 Java 8 日期类型，如 Date）
        objectMapper.setDateFormat(new SimpleDateFormat(DATE_TIME_FORMAT));

        // 序列化时，跳过值为 null 的字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 允许单引号、允许不带引号的字段名
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

        // 美化输出 JSON
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        // 处理空字符串为 null 的情况
        SimpleModule module = new SimpleModule();
        module.addDeserializer(String.class, new StringDeserializer()
        {
            @Override
            public String deserialize(JsonParser jsonParser, com.fasterxml.jackson.databind.DeserializationContext ctxt) throws java.io.IOException
            {
                String result = super.deserialize(jsonParser, ctxt);
                return "".equals(result) ? null : result;
            }
        });
        objectMapper.registerModule(module);

        return objectMapper;
    }
}
